/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-05-26 10:40:02
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-08-08 17:43:18
 * @FilePath: \cxl-h5\src\router\limit.ts
 */
import { userStore } from '@/store/user.store'
import router from './index'

// 路由跳转前判断用户是否登录
class Limit {
    uStore: any
    constructor() {
        this.uStore = userStore()
    }
    init() {
        router.beforeEach((to, from, next) => {
            console.log('from', from)
            this.uStore.prevRouterName = from.name as string
            if (this.uStore.token === '') {
                //根据路由加载时，设置name，来判断当前路由是否可以访问
                if (
                    [
                        'login',
                        'register',
                        'retrieve',
                        'protocol',
                        'index',
                        'webview',
                        'message-list',
                        'message-detailed',
                        'collision',
                        'new-energy'
                    ].includes(to.name as string)
                ) {
                    next()
                } else {
                    //返回到首页
                    next({ name: 'index' })
                }
            } else {
                //根据路由中的权限配置，判断当前页面是否有权访问
                if ((to.meta.permission as string[]).includes('admin') && !this.uStore.isAdmin) {
                    next({ name: 'no-permission' })
                } else {
                    next()
                }
            }
            if (to.meta.title) {
                // 判断是否有标题
                document.title = to.meta.title as string
            }
        })
    }
}

export default Limit
